package com.cmc.cloud.cmclink.doc.controller.admin.multimodaltransport;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.cmc.cloud.cmclink.doc.api.document.emums.ExImTypeEnum;
import com.cmc.cloud.cmclink.doc.api.document.emums.MulitOpOperationTypeEnum;
import com.cmc.cloud.cmclink.doc.api.document.emums.SoSiEnum;
import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.entity.BlnoDO;
import com.cmc.cloud.cmclink.doc.rpcservice.CustomerRpcService;
import com.cmc.cloud.cmclink.doc.service.multimodaltransport.MultiOpService;
import com.cmc.cloud.cmclink.doc.service.si.BlnoService;
import com.cmc.cloud.cmclink.doc.service.so.AttachmentService;
import com.cmc.cloud.cmclink.doc.vo.blnovo.opbargeagentbroker.*;
import com.cmc.cloud.cmclink.doc.vo.multimodaltransport.multiop.*;
import com.cmc.cloud.cmclink.doc.vo.sovo.attachmentvo.AttachmentBaseVO;
import com.cmc.cloud.cmclink.system.api.api.file.FileApi;
import com.cmc.cloud.cmclink.system.api.api.file.dto.FileBatchReqDTO;
import com.cmc.cloud.cmclink.system.api.api.file.dto.FileMetaInfoRespDTO;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.operatelog.core.annotations.OperateLog;
import com.cmes.framework.operatelog.core.enums.OperateTypeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 进口-设置驳船代理报关公司，前端接口Controller
 * 根据类型单独出接口 各种类型的校验、页面、权限、逻辑、日志均不相同，不可放在一个接口中
 * @author codegen
 */
@Tag(name = "管理后台 - 进口-设置驳船代理报关公司")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL + "/multi-op/BargeAgentBroker/im")
public class MultiOpBargeAgentBrokerController {

    @Resource
    private MultiOpService multiOpService;
    @Resource
    private CustomerRpcService nameTransferService;

    @Resource
    private BlnoService blnoService;
    @Resource
    private AttachmentService attachmentService;

    @Resource
    private FileApi fileApi;
    /**
     * 根据类型单独出接口 各种类型的校验、页面、权限、逻辑、日志均不相同，不可放在一个接口中
     * @param pageVo
     * @return
     */
    @OperateLog(type = OperateTypeEnum.GET)
    @Operation(summary = "im 获得分页")
    @PostMapping("/page")
    public CommonResult<PageResult<MultiOpBargeAgentBrokerRespVO>>
    imPage(@Valid @RequestBody MultiOpBargeAgentBrokerPageReqVO pageVo) {
        PageResult<MultiOpBargeAgentBrokerRespVO> pageResult = multiOpService.imPageBargeAgentBroker(pageVo);
        nameTransferService.fillCompanyNameByBkpCodeFunctionally(
                pageResult.getList(),
                // 提取bkpCode的函数
                MultiOpBargeAgentBrokerRespVO::getBarge,
                // 设置本地名称的函数
                MultiOpBargeAgentBrokerRespVO::setBargeNameLocal,
                // 设置英文名称的函数
                MultiOpBargeAgentBrokerRespVO::setBargeNameEn
        );
        nameTransferService.fillCompanyNameByBkpCodeFunctionally(
                pageResult.getList(),
                // 提取bkpCode的函数
                MultiOpBargeAgentBrokerRespVO::getCustomBroker,
                // 设置本地名称的函数
                MultiOpBargeAgentBrokerRespVO::setCustomBrokerNameLocal,
                // 设置英文名称的函数
                MultiOpBargeAgentBrokerRespVO::setCustomBrokerNameEn
        );
        nameTransferService.fillCompanyNameByBkpCodeFunctionally(
                pageResult.getList(),
                // 提取bkpCode的函数
                MultiOpBargeAgentBrokerRespVO::getOperatingAgent,
                // 设置本地名称的函数
                MultiOpBargeAgentBrokerRespVO::setOperatingAgentNameLocal,
                // 设置英文名称的函数
                MultiOpBargeAgentBrokerRespVO::setOperatingAgentNameEn
        );
        return CommonResult.success(pageResult);
    }
    /**
     * setCommodityCn
     *
     * @param reqVO
     */
    @Operation(summary = "设置中文品名")
    @PostMapping("/setCommodityCn")
    public CommonResult<Void> setCommodityCn(@Valid @RequestBody BlnoOperateCommodityCnReqVO reqVO) {
        blnoService.setCommodityCn(reqVO.getBlnoIds(), reqVO.getCommodityCn() );
        return CommonResult.success();
    }
    /**
     * 设置海船卸货码头
     *
     * @param reqVO
     */
    @Operation(summary = "设置海船卸货码头")
    @PostMapping("/setLinerTerminal")
    public CommonResult<Void> setLinerTerminal(@Valid @RequestBody BlnoOperateLinerTerminalReqVO reqVO) {

        multiOpService.setOp(reqVO.getBlnoIds(),reqVO.getLinerTerminal(),reqVO.getRemark(),null, MulitOpOperationTypeEnum.LINER_TERMINAL, ExImTypeEnum.IM);
        return CommonResult.success();
    }
    /**
     * 设置驳船公司
     *
     * @param reqVO
     */
    @Operation(summary = "设置驳船公司")
    @PostMapping("/setBarge")
    public CommonResult<Void> setBarge(@Valid @RequestBody BlnoOperateBargeReqVO reqVO) {
        multiOpService.setOp(reqVO.getBlnoIds(),reqVO.getBarge(),reqVO.getRemark(),null, MulitOpOperationTypeEnum.BARGE, ExImTypeEnum.IM);
        return CommonResult.success();
    }
    /**
     * 设置报关公司
     *
     * @param reqVO
     */
    @Operation(summary = "设置报关公司")
    @PostMapping("/setCustomBroker")
    public CommonResult<Void> setCustomBroker(@Valid @RequestBody BlnoOperateCustomBrokerReqVO reqVO) {
        multiOpService.setOp(reqVO.getBlnoIds(),reqVO.getCustomBroker(),reqVO.getRemark(),null, MulitOpOperationTypeEnum.CUSTOM_BROKER, ExImTypeEnum.IM);
        return CommonResult.success();
    }
    /**
     * 设置操作代理
     *
     * @param reqVO
     */
    @Operation(summary = "设置操作代理")
    @PostMapping("/setOperationAgent")
    public CommonResult<Void> setOperationAgent(@Valid @RequestBody BlnoOperateOperationAgentReqVO reqVO) {
        multiOpService.setOp(reqVO.getBlnoIds(),reqVO.getOperationAgent(),reqVO.getRemark(),null, MulitOpOperationTypeEnum.OPERATION_AGENT, ExImTypeEnum.IM);
        return CommonResult.success();
    }
    /**
     * 其他设置
     *
     * @param reqVO
     */
    @Operation(summary = "其他设置")
    @PostMapping("/setOther")
    public CommonResult<Void> setOther(@Valid @RequestBody BlnoOperateOtherReqVO reqVO) {
        multiOpService.setOp(reqVO.getBlnoIds(),reqVO.getContractNo(),null,null, MulitOpOperationTypeEnum.CONTRACT_NO, ExImTypeEnum.IM);
        multiOpService.setOp(reqVO.getBlnoIds(),reqVO.getCustomVoyage(),null,null, MulitOpOperationTypeEnum.CUSTOM_VOYAGE, ExImTypeEnum.IM);
        multiOpService.setOp(reqVO.getBlnoIds(),reqVO.getCustomDestination(),null,null, MulitOpOperationTypeEnum.CUSTOM_DESTINATION, ExImTypeEnum.IM);
        return CommonResult.success();
    }
    /**
     * 查看附件列表
     * /admin-api/system/file/meta-info/1984172726297894912
     * {"code":0,"data":{"id":"1984172726297894912","innerServiceName":"cmclink-ibusiness-server","fileFormat":"xlsx","fileName":"TLX白名单 (1)","fileSize":3629.00,"fileBusinessType":"C03","fileBusinessPoint":"订舱","createTime":"2025-10-31T16:16:57+0800"},"msg":""}
     * /admin-api/system/file/download-url/1984172726297894912
     * {"code":0,"data":"https://cos-di.sinolines.com.cn//cos-download/v1/pvf/1/cmclinks-private-cos/ba30387c6633954e0271122f8f1b41bd/TLX白名单 (1).xlsx?expires=1761905816760&signature=0101EhRCzjRM:NEM4M0MxN0VGNzE2QTE4MzA5Q0UwREMwQzc3MDI0NTc2MTU0QzBDNw==","msg":""}
     * @param reqVO
     */
    @UseResponsePropertyAdvice
    @Operation(summary = "查看附件列表")
    @PostMapping("/listAttachment")
    public CommonResult<List<BlnoAttachmentReqVO>> listAttachment(@Valid @RequestBody BlnoOperateIdsReqVO reqVO) {
        List<BlnoAttachmentReqVO> attachmentUpdateReqVos = BeanUtil.copyToList(attachmentService.seleteByReferenceIds(reqVO.getBlnoIds(), SoSiEnum.SI.getValue()),
                BlnoAttachmentReqVO.class);
        if(!attachmentUpdateReqVos.isEmpty()){
            List<BlnoDO> blnoList = blnoService.getBlnoList(reqVO.getBlnoIds());
            Map<Long, List<BlnoDO>> collect = blnoList.stream().collect(Collectors.groupingBy(BlnoDO::getId));
            if(!collect.isEmpty()){
                for (BlnoAttachmentReqVO attachmentUpdateReqVO : attachmentUpdateReqVos) {
                    List<BlnoDO> blnoDos = collect.get(attachmentUpdateReqVO.getReferenceId());
                    if(blnoDos!=null && !blnoDos.isEmpty()){
                        BlnoDO blnoDO = blnoDos.get(0);
                        attachmentUpdateReqVO.setBlNo(blnoDO.getBlNo());
                    }
                }
            }

            FileBatchReqDTO fileBatchReqDTO = new FileBatchReqDTO();
            fileBatchReqDTO.setIds(attachmentUpdateReqVos.stream().map(AttachmentBaseVO::getFileId).collect(Collectors.toList()));

            try {
                CommonResult<List<FileMetaInfoRespDTO>> result = fileApi.listMetaInfo(fileBatchReqDTO);
                List<FileMetaInfoRespDTO> checkedData = result.getCheckedData();
                if (CollectionUtil.isNotEmpty(checkedData)) {
                    Map<Long, List<FileMetaInfoRespDTO>> map = checkedData.stream().collect(Collectors.groupingBy(FileMetaInfoRespDTO::getId));

                    for (BlnoAttachmentReqVO attachmentUpdateReqVO : attachmentUpdateReqVos) {
                        List<FileMetaInfoRespDTO> fileList = map.get(attachmentUpdateReqVO.getFileId());
                        if (CollectionUtil.isNotEmpty(fileList)) {
                            FileMetaInfoRespDTO fileInfo = fileList.get(0);
                            attachmentUpdateReqVO.setFileSize(fileInfo.getFileSize());
                        }
                    }

                    return CommonResult.success(attachmentUpdateReqVos);
                } else {
                    return CommonResult.success();
                }
            } catch (Exception e) {
                return CommonResult.success();
            }
        }

        return CommonResult.success();
        }
    /**
     * sendEmail
     *
     * @param reqVO
     */
    @Operation(summary = "sendEmail")
    @PostMapping("/sendEmail")
    public CommonResult<Void> sendEmail(@Valid @RequestBody BlnoOperateSendEmailReqVO reqVO) {
        //todo send email
        return CommonResult.success();
    }
}
